#include <functional>
#include <iostream>
#include <string.h>
#include <memory>
#include <cstdint>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "InetAddr.hpp"

void Usage(std::string name)
{
   std::cout << "usage:\n\t" << name << " serveip serveport\n"
             << std::endl;
}

int main(int argc, char *argv[])
{
   if (argc != 3)
   {
      Usage(argv[0]);
      exit(1);
   }
   std::string server_ip = argv[1];
   uint16_t server_prot = std::stoi(argv[2]);
   // 创建套接字
   int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
   if (sockfd < 0)
   {
      std::cerr << "socket error" << std::endl;
      exit(2);
   }
   // 设置本地信息
   struct sockaddr_in server;
   memset(&server, 0, sizeof(server));
   server.sin_family = AF_INET;
   server.sin_port = htons(server_prot);
   server.sin_addr.s_addr = inet_addr(server_ip.c_str());
   // 连接套接字sockfd
   int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
   if (n < 0)
   {
      std::cerr << "connect error" << std::endl;
      exit(3);
   }
   while (true)
   {
      std::cout << "please enter#:" << std::endl;
      std::string outstring;
      std::getline(std::cin, outstring);
      ssize_t s = send(sockfd, outstring.c_str(), outstring.size(), 0); // 发送信息
      if (s > 0)
      {
         // 发送成功
         char buffer[1024];
         ssize_t n = recv(sockfd, buffer, sizeof(buffer) - 1, 0); // 接受信息
         if (n > 0)
         {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
         }
         else
         {
            break;
         }
      }
      else
      {
         break;
      }
   }
   close(sockfd);
   return 0;
}